package cn.edkuir.order.service.impl;

import cn.edkuir.common.to.SkuHasStockVo;
import cn.edkuir.common.to.mq.SeckillOrderTo;
import cn.edkuir.common.utils.R;
import cn.edkuir.common.vo.MemberRespVo;
import cn.edkuir.order.constant.OrderConstant;
import cn.edkuir.order.entity.OrderItemEntity;
import cn.edkuir.order.entity.PaymentInfoEntity;
import cn.edkuir.order.enume.OrderStatusEnum;
import cn.edkuir.order.feign.CartFeignService;
import cn.edkuir.order.feign.MemberFeignService;
import cn.edkuir.order.feign.ProductFeignService;
import cn.edkuir.order.feign.WareFeignService;
import cn.edkuir.order.interceptor.LoginUserInterceptor;
import cn.edkuir.order.service.OrderItemService;
import cn.edkuir.order.service.PaymentInfoService;
import cn.edkuir.order.to.OrderCreateTo;
import cn.edkuir.order.vo.*;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.edkuir.common.utils.PageUtils;
import cn.edkuir.common.utils.Query;

import cn.edkuir.order.dao.OrderDao;
import cn.edkuir.order.entity.OrderEntity;
import cn.edkuir.order.service.OrderService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;


@Service("orderService")
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {

    private ThreadLocal<OrderSubmitVo> orderSubmitVoThreadLocal = new ThreadLocal<>();

    @Autowired
    private MemberFeignService memberFeignService;
    @Autowired
    private CartFeignService cartFeignService;
    @Autowired
    private ThreadPoolExecutor executor;
    @Autowired
    private WareFeignService wareFeignService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private ProductFeignService productFeignService;
    @Autowired
    private OrderItemService orderItemService;
    @Autowired
    private PaymentInfoService paymentInfoService;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>()
        );

        return new PageUtils(page);
    }


    //构建当前登录用户的订单页
    @Override
    public OrderConfirmVo confirmOrder() throws ExecutionException, InterruptedException {
        OrderConfirmVo orderConfirmVo = new OrderConfirmVo();
        MemberRespVo memberRespVo = LoginUserInterceptor.loginUser.get();

        //获取主线程上的老请求数据, 防止异步调用threadlocal无法获取
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();

        CompletableFuture<Void> getAddressTask = CompletableFuture.runAsync(() -> {
            //1. 远程查询所有的收货地址列表
            RequestContextHolder.setRequestAttributes(requestAttributes);
            List<MemberAddressVo> addressList = memberFeignService.getAddressList(memberRespVo.getId());
            orderConfirmVo.setAddressList(addressList);
        }, executor);


        CompletableFuture<Void> cartItemsTask = CompletableFuture.runAsync(() -> {
            //2. 远程查询购物车所有选中的购物项
            RequestContextHolder.setRequestAttributes(requestAttributes);
            List<OrderItemVo> cartItems = cartFeignService.getCurrentUserCartItems();
            orderConfirmVo.setItems(cartItems);
        }, executor).thenRunAsync(() -> {
            //3. 库存系统查询每个sku是否有货
            List<OrderItemVo> items = orderConfirmVo.getItems();
            List<Long> skuIds = items.stream().map(OrderItemVo::getSkuId).collect(Collectors.toList());

            R r = wareFeignService.HasStock(skuIds);
            List<SkuHasStockVo> skuHasStockVos = r.getData(new TypeReference<List<SkuHasStockVo>>() {
            });

            if(!CollectionUtils.isEmpty(skuHasStockVos)) {
                //加工成map
                Map<Long, Boolean> stocks = skuHasStockVos.stream()
                        .collect(Collectors.toMap(SkuHasStockVo::getSkuId, SkuHasStockVo::isHasStock));
                orderConfirmVo.setStocks(stocks);
            }
        }, executor);


        //4. 查询用户积分
        Integer integration = memberRespVo.getIntegration();
        orderConfirmVo.setIntegration(integration);

        //5. 其他数据自动计算

        //6. 防重令牌
        String token = UUID.randomUUID().toString().replace("-", "");
        //redis保存一份令牌, 设置过期时间
        stringRedisTemplate.opsForValue().set(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberRespVo.getId(),
                token, 30, TimeUnit.MINUTES);
        orderConfirmVo.setOrderToken(token);

        CompletableFuture.allOf(getAddressTask, cartItemsTask).get();

        return orderConfirmVo;
    }



    //下单
//    @GlobalTransactional  高并发场景不适用
    @Transactional
    @Override
    public SubmitRespVo submitOrder(OrderSubmitVo orderSubmitVo) {
        orderSubmitVoThreadLocal.set(orderSubmitVo);
        SubmitRespVo submitRespVo = new SubmitRespVo();
        submitRespVo.setCode(0);
        MemberRespVo memberRespVo = LoginUserInterceptor.loginUser.get();

        //1. 验证令牌(令牌的验证和删除必须保证原子性)
        //0 - 失败, 1 - 成功
        String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
        String orderToken = orderSubmitVo.getOrderToken();
//        String serverToken = stringRedisTemplate.opsForValue().get(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberRespVo.getId());

        Long res = stringRedisTemplate.execute(new DefaultRedisScript<>(script, Long.class),
                Collections.singletonList(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberRespVo.getId()),    //keys
                orderToken);
        if(res == 0L) {
            //令牌验证失败
            submitRespVo.setCode(1);
            return submitRespVo;
        }

        //2. 创建订单, 订单项等信息
        OrderCreateTo orderCreateTo = createOrder();

        //3. 验价
        BigDecimal payAmount = orderCreateTo.getOrderEntity().getPayAmount();
        BigDecimal payPrice = orderSubmitVo.getPayPrice();
        if(Math.abs(payAmount.subtract(payPrice).doubleValue()) >= 0.01) {
            //对比失败, 差价在0.01以上
            submitRespVo.setCode(2);
            return submitRespVo;
        }

        //4. 保存订单到数据库
        saveOrder(orderCreateTo);

        //5. 锁定库存, 只要有异常就回滚数据
        WareSkuLockVo wareSkuLockVo = new WareSkuLockVo();
        wareSkuLockVo.setOrderSn(orderCreateTo.getOrderEntity().getOrderSn());
        List<OrderItemVo> orderItemVos = orderCreateTo.getOrderItems().stream().map(item -> {
            OrderItemVo orderItemVo = new OrderItemVo();
            orderItemVo.setSkuId(item.getSkuId());
            orderItemVo.setCount(item.getSkuQuantity());
            orderItemVo.setTitle(item.getSkuName());
            return orderItemVo;
        }).collect(Collectors.toList());
        wareSkuLockVo.setLocks(orderItemVos);
        R r = wareFeignService.lockOrderWare(wareSkuLockVo);
        if((int) r.get("code") != 0) {
            //库存锁定失败
            submitRespVo.setCode(3);
            return submitRespVo;
        }
        submitRespVo.setOrderEntity(orderCreateTo.getOrderEntity());
        //int i = 10 / 0;
        return submitRespVo;
    }


    //获取当前订单的支付信息
    @Override
    public PayVo getOrderPayVo(String orderSn) {
        OrderEntity orderEntity = baseMapper.selectOne(new QueryWrapper<OrderEntity>().eq("order_sn", orderSn));
        PayVo payVo = new PayVo();
        payVo.setBody("谷粒商城");
        payVo.setOut_trade_no(orderSn);
        payVo.setSubject("谷粒商城");
        payVo.setTotal_amount(orderEntity.getPayAmount().setScale(2, BigDecimal.ROUND_UP).toString());

        return payVo;
    }



    //处理支付宝异步支付结果
    @Transactional
    @Override
    public String handlePayResp(PayAsyncVo payAsyncVo) {
        try {
            //1.保存交易流水
            PaymentInfoEntity paymentInfoEntity = new PaymentInfoEntity();
            paymentInfoEntity.setAlipayTradeNo(payAsyncVo.getTrade_no());
            paymentInfoEntity.setOrderSn(payAsyncVo.getOut_trade_no());
            paymentInfoEntity.setPaymentStatus(payAsyncVo.getTrade_status());
            paymentInfoService.save(paymentInfoEntity);

            //2.修改订单状态信息
            String status = payAsyncVo.getTrade_status();
            if(status.equals("TRADE_SUCCESS") || status.equals("TRADE_FINISH")) {
                String tradeNo = payAsyncVo.getOut_trade_no();
                baseMapper.updateOrderStatus(tradeNo, OrderStatusEnum.PAYED.getCode());
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "error";
        }

        return "success";
    }


    //创建秒杀订单
    @Override
    @Transactional
    public void createSeckillOrder(SeckillOrderTo seckillOrderTo) {
        //保存订单信息
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setOrderSn(seckillOrderTo.getOrderSn());
        orderEntity.setMemberId(seckillOrderTo.getMemberId());
        orderEntity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        orderEntity.setPayAmount(seckillOrderTo.getSeckillPrice().multiply(new BigDecimal(seckillOrderTo.getNum().toString())));
        this.save(orderEntity);

        //保存订单项信息
        OrderItemEntity orderItemEntity = new OrderItemEntity();
        orderEntity.setOrderSn(orderEntity.getOrderSn());
        orderItemEntity.setRealAmount(orderEntity.getPayAmount());
        orderItemEntity.setSkuQuantity(seckillOrderTo.getNum());
        //...
        orderItemService.save(orderItemEntity);
    }


    //分页查询当前登录用户的订单信息
    @Override
    public PageUtils queryPageWithItem(Map<String, Object> params) {
        MemberRespVo memberRespVo = LoginUserInterceptor.loginUser.get();

        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>().eq("member_id", memberRespVo.getId()).orderByDesc("id")
        );

        List<OrderEntity> orderEntities = page.getRecords().stream().map(order -> {
            order.setItems(orderItemService.list(new QueryWrapper<OrderItemEntity>().eq("order_sn", order.getOrderSn())));
            return order;
        }).collect(Collectors.toList());
        page.setRecords(orderEntities);

        return new PageUtils(page);
    }


    //保存订单数据到数据库
    private void saveOrder(OrderCreateTo orderCreateTo) {
        OrderEntity order = orderCreateTo.getOrderEntity();
        List<OrderItemEntity> orderItems = orderCreateTo.getOrderItems();

        order.setModifyTime(new Date());
        order.setCreateTime(new Date());
        this.save(order);

        orderItemService.saveBatch(orderItems);
    }



    private OrderCreateTo createOrder() {
        OrderCreateTo orderCreateTo = new OrderCreateTo();
        OrderSubmitVo orderSubmitVo = orderSubmitVoThreadLocal.get();

        //1.获取订单信息
        OrderEntity orderEntity = buildOrder(orderSubmitVo);

        //2.获取到所有的订单项信息
        List<OrderItemEntity> orderItemEntities = buildOrderItems(orderEntity.getOrderSn());

        //3.计算价格, 积分相关数据
        computePrice(orderEntity, orderItemEntities);

        orderCreateTo.setOrderEntity(orderEntity);
        orderCreateTo.setOrderItems(orderItemEntities);

        return orderCreateTo;
    }



    //计算价格相关
    private void computePrice(OrderEntity orderEntity, List<OrderItemEntity> orderItemEntities) {
        BigDecimal total = new BigDecimal("0");
        BigDecimal coupon = new BigDecimal("0");
        BigDecimal integration = new BigDecimal("0");
        BigDecimal promotion = new BigDecimal("0");
        //1.价格相关
        //订单总额, 叠加每一个订单项的金额
        for (OrderItemEntity orderItemEntity : orderItemEntities) {
            total = total.add(orderItemEntity.getRealAmount());
            integration = integration.add(orderItemEntity.getIntegrationAmount());
            coupon = coupon.add(orderItemEntity.getCouponAmount());
            promotion = promotion.add(orderItemEntity.getPromotionAmount());
        }
        //应付总额
        orderEntity.setTotalAmount(total);
        orderEntity.setPayAmount(total.add(orderEntity.getFreightAmount()));

        //2.积分信息
        orderEntity.setCouponAmount(coupon);
        orderEntity.setIntegrationAmount(integration);
        orderEntity.setPromotionAmount(promotion);

        //3.其他
        orderEntity.setDeleteStatus(0); //未删除
    }



    //构建订单
    private OrderEntity buildOrder(OrderSubmitVo orderSubmitVo) {
        MemberRespVo memberRespVo = LoginUserInterceptor.loginUser.get();
        OrderEntity orderEntity = new OrderEntity();
        //1. 生成订单号
        String orderSn = IdWorker.getTimeId();
        orderEntity.setOrderSn(orderSn);
        //会员id
        orderEntity.setMemberId(memberRespVo.getId());

        //2. 设置收货地址信息和运费
        R r = wareFeignService.getFare(orderSubmitVo.getAddrId());
        FareVo fareVo = r.getData(new TypeReference<FareVo>() {
        });
        //运费信息
        orderEntity.setFreightAmount(fareVo.getFare());
        //收货人信息
        orderEntity.setReceiverCity(fareVo.getAddress().getCity());
        orderEntity.setReceiverDetailAddress(fareVo.getAddress().getDetailAddress());
        orderEntity.setReceiverName(fareVo.getAddress().getName());
        orderEntity.setReceiverPhone(fareVo.getAddress().getPhone());
        orderEntity.setReceiverPostCode(fareVo.getAddress().getPostCode());
        orderEntity.setReceiverProvince(fareVo.getAddress().getProvince());
        orderEntity.setReceiverRegion(fareVo.getAddress().getRegion());

        //3.设置订单状态信息
        orderEntity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        orderEntity.setAutoConfirmDay(7);

        return orderEntity;
    }



    //构建所有订单项
    private List<OrderItemEntity> buildOrderItems(String orderSn) {
        //最后确定每个购物项的价格
        List<OrderItemVo> cartItems = cartFeignService.getCurrentUserCartItems();
        if(!CollectionUtils.isEmpty(cartItems)) {
            return cartItems.stream().map(cartItem -> {
                OrderItemEntity orderItemEntity = buildOrderItem(cartItem);
                orderItemEntity.setOrderSn(orderSn);
                return orderItemEntity;
            }).collect(Collectors.toList());
        }
        return null;
    }



    //构建某一个指定订单项
    private OrderItemEntity buildOrderItem(OrderItemVo orderItemVo) {
        OrderItemEntity orderItemEntity = new OrderItemEntity();
        //1.订单信息: 订单号
        //2.spu信息
        Long skuId = orderItemVo.getSkuId();
        R r = productFeignService.SpuInfoBySkuId(skuId);
        SpuInfoVo spuInfoVo = r.getData(new TypeReference<SpuInfoVo>() {
        });
        orderItemEntity.setSpuId(spuInfoVo.getId());
        orderItemEntity.setSpuBrand(spuInfoVo.getBrandId().toString());
        orderItemEntity.setSpuName(spuInfoVo.getSpuName());
        orderItemEntity.setCategoryId(spuInfoVo.getCatalogId());

        //3.sku信息
        orderItemEntity.setSkuId(skuId);
        orderItemEntity.setSkuName(orderItemVo.getTitle());
        orderItemEntity.setSkuPic(orderItemVo.getImage());
        orderItemEntity.setSkuPrice(orderItemVo.getPrice());
        orderItemEntity.setSkuAttrsVals(StringUtils.collectionToDelimitedString(orderItemVo.getSkuAttr(), ";"));
        orderItemEntity.setSkuQuantity(orderItemVo.getCount());

        //4.优惠信息
        //5.积分信息
        orderItemEntity.setGiftGrowth(orderItemVo.getPrice().intValue());
        orderItemEntity.setGiftIntegration(orderItemVo.getPrice().intValue());

        //6.订单项的价格信息
        orderItemEntity.setPromotionAmount(new BigDecimal("0"));
        orderItemEntity.setCouponAmount(new BigDecimal("0"));
        orderItemEntity.setIntegrationAmount(new BigDecimal("0"));
        //当前订单项的实际金额
        BigDecimal origin = orderItemEntity.getSkuPrice().multiply(new BigDecimal(orderItemEntity.getSkuQuantity().toString()));
        orderItemEntity.setRealAmount(origin
                .subtract(orderItemEntity.getPromotionAmount())
                .subtract(orderItemEntity.getCouponAmount())
                .subtract(orderItemEntity.getIntegrationAmount()));

        return orderItemEntity;
    }

}